const router = require('koa-router')()

router.prefix('/login')

// 生成token
const jwt = require('jsonwebtoken');
const koaJwt = require('koa-jwt');

// 引入解密模块
const JSEncrypt = require('node-jsencrypt');



// 生成雪花ID的方法
const createSnow = function (ctx) {
  let snowFlake = ctx.snowFlake;
  let snowId = snowFlake.createSnow(1);
  return snowId;
}



router.get("/getPublicKey", async (ctx, next) => {
  console.log("123456 ");
  let snowFlake = ctx.snowFlake;
  let snowId = snowFlake.createSnow(1);
  console.log(snowId, "这个是雪花ID");
  console.log(ctx.config);
  ctx.body = { publicKey: ctx.state.publicKey };
})

router.post('/submit', async (ctx, next) => {
  let data = ctx.request.body;
  // 创建decrypt对象，对密码进行解密
  const decrypt = new JSEncrypt();
  decrypt.setPrivateKey(ctx.state.privateKey);
  let sql = 'select * from user'
  let res = await ctx.db.EXCUTE(sql, []);
  console.log(res);
  let obj = res.find(i => { console.log(i.user_password, "解密之前的"); return i.user_name == data.username && decrypt.decrypt(i.user_password) == decrypt.decrypt(data.password) });

  if (obj) {
    const user = { username: data.username };
    // 从全局变量中拿出secretKey
    // 生成 token
    const token = jwt.sign(user, ctx.config.secretKey, { expiresIn: '3h' });
    const refreshToken = jwt.sign({ auth: true }, ctx.config.secretKey, { expiresIn: '7d' });
    let user_info;
    // 通过身份来查询其对应的信息
    if (obj.user_auth === "student_per") {
      let sql = "select student.user_id, student.user_name, student.student_name, student.signature, student.class_id, student.grade_id, student.institute_id, student.student_id, student.avatar, class.class_name, grade.grade_name, institute.institute_name from student join class on student.class_id = class.class_id join grade on student.grade_id = grade.grade_id join institute on student.institute_id = institute.institute_id where student.user_id = ?";
      let res = await ctx.db.EXCUTE(sql, [obj.user_id]);
      user_info = res[0]
    } else if (obj.user_auth === 'teacher_per') {
      let sql = "select teacher.user_id, teacher.teacher_name, teacher.user_name, teacher.signature, teacher.institute_id, teacher.teacher_id, teacher.avatar, institute.institute_name from teacher join institute on teacher.institute_id = institute.institute_id where teacher.user_id = ?";
      let res = await ctx.db.EXCUTE(sql, [obj.user_id]);
      user_info = res[0];
    }
    user_info = { ...user_info, user_auth: obj.user_auth }
    user_info = ctx.Aes.aesEncrypt(ctx, JSON.stringify(user_info))
    ctx.body = { code: 200, msg: "成功登陆", token, refreshToken, user_info: user_info }
  } else {
    ctx.body = { code: 500, type: "error", msg: "用户名或密码错误" }
  }
})

router.post("/userInfo", async (ctx, next) => {
  let data = ctx.request.body;
  let user_info = JSON.parse(ctx.Aes.aesDecrypt(ctx, data.user_info));
  ctx.body = { user_info };
})



module.exports = router